import {useCallback} from "react";
import {usePagination} from "ahooks";
import {FormInstance} from "antd";


type Service = (...args: any) => Promise<any>

interface Options {
    defaultPageSize?: number
    manual?: boolean // 是否手动触发
}

/**
 * 返回
 *  reload 修改参数后返回第一次调用
 *  refresh 当前分页刷新
 *
 * @param service
 * @param form
 * @param options
 */
const useSearchTable: (service: Service, form?: FormInstance, options?: Options) => {
    search: (params?: any) => void,
    refresh: (params?: any) => void,
    getOrder: (index: number) => string | number,
    tableProps: {
        loading: boolean,
        dataSource: any[],
        pagination: any
    }
} = (service, form?, options?) => {

    const defaultPageSize = options?.defaultPageSize || 20;

    const {
        loading,
        data,
        pagination,
        refresh,
        run
    } = usePagination((params: any) => {
        if (form) {
            params = {...form.getFieldsValue(), ...params}
        }
        return service(params)
    }, {
        manual: options?.manual || false,
        defaultPageSize: defaultPageSize
    })

    const search = useCallback(
        (params?: any) => {
            return run({
                current: 1,
                pageSize: defaultPageSize,
                ...params
            })
        },
        [defaultPageSize, run]
    )

    // 根据index和分页获取序号
    const getOrder = useCallback((index: number) => {
        const {current, pageSize} = pagination;
        return loading ? '-' : pageSize * (current - 1) + index + 1
    }, [pagination, loading])

    const showTotal = useCallback((total: number, range: Array<number>) => {
        const rangeStr = range[0] === range[1] ? range[0] : `${range[0]}-${range[1]}`;
        return `共${total}条数据，当前显示第${rangeStr}条`;
    }, [])

    return {
        search,
        refresh,
        getOrder,
        run,
        tableProps: {
            loading,
            dataSource: data?.list || [],
            pagination: {
                ...pagination,
                showTotal,
                size: 'small'
            },
        }
    }
}

export default useSearchTable

